/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package demisemapping;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import javax.swing.JFrame;

/**
 *
 * @author trbot
 */
public class PreviewJFrame extends JFrame implements GameNode {
    public final static int WIDTH = 400;
    public final static int HEIGHT = 300;

    private volatile BufferedImage img;
    private final int imageIndex;
    
    public PreviewJFrame(int imageIndex) {
        this.imageIndex = imageIndex;
        
        setTitle("Preview Frame for index " + imageIndex);
        setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        setLayout(new GridLayout(1, 0));
        
        setBackground(Color.BLACK);
        setPreferredSize(new Dimension(WIDTH, HEIGHT));
        setVisible(true);
        pack();
        //int left = 1680, top = 0;
        int left = 300+imageIndex*WIDTH, top = 700;
        //int left = 840, top = 30;
        setLocation(left, top);
        
        createBufferStrategy(2);
    }

    public void notifyOfGame(int mode, ArrayList<BufferedImage> images, ArrayList<int[]> shots, int[] w, int[] h) {
//        BufferedImage bi = new BufferedImage(w[imageIndex], h[imageIndex], BufferedImage.TYPE_INT_RGB);
//        
//        WritableRaster r = (WritableRaster) bi.getData();
//        r.setPixels(0, 0, w[imageIndex], h[imageIndex], shots.get(imageIndex));
//        
//        this.img = bi;
        this.img = images.get(imageIndex);
        repaint();
    }

    @Override
    public void paint(Graphics _g) {
        //super.paint(g);
        Graphics2D g = (Graphics2D) _g;
        
        // prepare back buffer for double buffered drawing
        BufferedImage backbuffer = new BufferedImage(
                getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
        Graphics2D gg = backbuffer.createGraphics();
        gg.setBackground(Color.GRAY);
        gg.clearRect(0, 0, backbuffer.getWidth(), backbuffer.getHeight());
        
        if (img != null) {
            // draw img onto buffer
//            System.out.println("drawing img with height " + img.getHeight() + " and width " + img.getWidth());
            //gg.drawImage(img, 0, 0, this);
            gg.drawImage(img.getScaledInstance(WIDTH, HEIGHT, BufferedImage.SCALE_SMOOTH), 0, 0, this);
        }
        
        // draw buffer onto canvas
        //System.out.println("insets=" + getInsets().left + " " + getInsets().top);
        g.drawImage(backbuffer,
                    (getWidth()-backbuffer.getWidth())/2+getInsets().left,
                    (getHeight()-backbuffer.getHeight())/2+getInsets().top,
                    this);
    }
}
